import type { ConfigProviderProps } from 'antd'
import { Root } from '@/types/menuItem'
import { createSlice } from '@reduxjs/toolkit'
import zhCN from 'antd/locale/zh_CN'

type Locale = ConfigProviderProps['locale']
export interface InitialState {
  Menus: Root
  tabItems: tabItem[]
  count: number
  selectedKeys: string[]
  activeKey: string
  definedLocale: string | null //自定义语言
  currentTheme: string | null // 主题
  antdLocale: Locale
}

interface tabItem {
  label: string
  key: string
  closable: boolean
}

const initialState: InitialState = {
  Menus: [],
  definedLocale: (localStorage.getItem('definedLocale') as string) || 'zh',
  currentTheme: localStorage.getItem('currentTheme') || 'light',
  antdLocale: JSON.parse(localStorage.getItem('antdLocale') as string) || zhCN,
  tabItems: [{ label: '首页', key: '/', closable: false }],
  selectedKeys: [''],
  activeKey: '/',
  count: 0
}

const frontStoreData = createSlice({
  name: 'front',
  initialState,
  reducers: {
    setMenus(state, action) {
      state.Menus = action.payload
    },
    // 自定义语言的切换
    changeDefinedLocale(state, { payload }) {
      state.definedLocale = payload
      localStorage.setItem('definedLocale', payload)
    },
    // 主题切换
    changeTheme(state, { payload }) {
      state.currentTheme = payload
      localStorage.setItem('currentTheme', payload)
    },
    // 切换antd语言
    changeAntdLocale(state, { payload }) {
      state.antdLocale = payload
      localStorage.setItem('antdLocale', JSON.stringify(payload))
    },
    setTabItems(state, action) {
      state.tabItems = action.payload
    },
    setSelectedKeys(state, action) {
      state.selectedKeys = action.payload
    },
    setActiveKey(state, action) {
      state.activeKey = action.payload
    }
  }
})
export const {
  setMenus,
  setTabItems,
  setSelectedKeys,
  setActiveKey,
  changeDefinedLocale,
  changeTheme,
  changeAntdLocale
} = frontStoreData.actions
const useFrontStore = frontStoreData.reducer

export default useFrontStore
